package com.sailboard.iot.opm.web.controller.equipment;

import com.github.pagehelper.PageInfo;
import com.sailboard.iot.opm.common.*;
import com.sailboard.iot.opm.dao.entity.*;
import com.sailboard.iot.opm.dao.entity.Console;
import com.sailboard.iot.opm.service.UserService;
import com.sailboard.iot.opm.service.company.CompanyService;
import com.sailboard.iot.opm.service.equipment.EquipmentConfigService;
import com.sailboard.iot.opm.service.equipment.EquipmentService;
import com.sailboard.iot.opm.service.qrcode.OssUtil;
import com.sailboard.iot.opm.utils.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * java类简单作用描述
 *
 * @ProjectName: iot-opm
 * @Package: com.sailboard.iot.opm.web.controller.equipment
 * @ClassName: ${TYPE_NAME}
 * @Description: java类作用描述
 * @Author: 候杰
 * @CreateDate: 2017/12/25 20:48
 * @UpdateUser: Neil.Zhou
 * @UpdateDate: 2017/12/25 20:48
 * @UpdateRemark: The modified content
 * @Version: 1.0
 * Copyright: Copyright (c) 2017
 */
@RestController
@RequestMapping("/v1/api0/")
public class EquipmentController {

    @Resource
    EquipmentService equipmentService;
    @Resource
    CompanyService companyService;
    @Resource
    UserService userService;
    @Resource
    EquipmentConfigService equipmentConfigService;

    private User getCurrent_user(){
        User current_user=new User();
        Subject currentUser = SecurityUtils.getSubject();//获取当前用户
        if(currentUser != null && currentUser.getPrincipals() != null) {
            String username = currentUser.getPrincipals().toString();
            current_user = userService.getByUsername(username);
        }
        return current_user;
    }

    //获取充电终端列表
    @RequestMapping(value = "equipment/terminalList")
    @ResponseBody
    public DataGrid<Terminal> terminalList(Integer page, Integer rows, Terminal terminal) {
        page = page == null ? 1 : page;
        rows = rows == null ? 10 : rows;
        terminal.setCreaterId(this.getCurrent_user().getCompanyId());//当前登陆人的公司（平台公司）
        PageInfo pageInfo = equipmentService.getTerminalList(page, rows, terminal);
        return new DataGrid(pageInfo);
    }

    //增加充电终端
    @RequestMapping(value = "equipment/addTerminal")
    @ResponseBody
    public JsonResult addTerminal(Terminal terminal) {
        if(terminal == null) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        if(StringUtils.isBlank(terminal.getMachineCode())) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "机器码不能为空");
        }
        if(StringUtils.isBlank(terminal.getBusinessCode())) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "业务码不能为空");
        }
        //机器码，业务码去重。
        if(equipmentService.getTerminalByMachineCode(terminal) != null){
            return new JsonResult(ResultCode.ERROR_CODE, "该机器码已存在");
        }
        if(equipmentService.getTerminalByBusinessCode(terminal) != null){
            return new JsonResult(ResultCode.ERROR_CODE, "该业务码已存在");
        }
        terminal.setCreaterId(this.getCurrent_user().getCompanyId());
        terminal.setCreater(this.getCurrent_user().getCompanyName());
        boolean isSuccess = equipmentService.addTerminal(terminal);
        return isSuccess ? JsonResult.success() : JsonResult.error();
    }
    //编辑终端
    @RequestMapping(value = "equipment/editTerminal")
    @ResponseBody
    public JsonResult editTerminal(Terminal terminal) {
        if(terminal == null || terminal.getId() == null) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        if(StringUtils.isBlank(terminal.getMachineCode())) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "机器码不能为空");
        }
        if(StringUtils.isBlank(terminal.getBusinessCode())) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "业务码不能为空");
        }
        //机器码，业务码去重。
        if(equipmentService.getTerminalByMachineCode(terminal) != null){
            return new JsonResult(ResultCode.ERROR_CODE, "该机器码已存在");
        }
        if(equipmentService.getTerminalByBusinessCode(terminal) != null){
            return new JsonResult(ResultCode.ERROR_CODE, "该业务码已存在");
        }
        boolean isSuccess = equipmentService.updateTerminal(terminal);
        return isSuccess ? JsonResult.success() : JsonResult.error();
    }

    //禁用终端
    @RequestMapping(value = "equipment/disableTerminal", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult disableTerminal(Long id) {
        if(id == null || id <= 0) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        boolean isSuccess = equipmentService.updateTerminalStatus(id, Constants.ROLE_STATUS_DISABLE);
        return isSuccess ? JsonResult.success() : JsonResult.error();
    }

    //启用终端
    @RequestMapping(value = "equipment/enableTerminal", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult enableTerminal(Long id) {
        if(id == null || id <= 0) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        boolean isSuccess = equipmentService.updateTerminalStatus(id, Constants.ROLE_STATUS_ENABLE);
        return isSuccess ? JsonResult.success() : JsonResult.error();
    }
    //删除终端
    @RequestMapping(value = "equipment/deleteTerminal", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult deleteTerminal(Long id) {
        if(id == null || id <= 0) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        boolean isSuccess = equipmentService.deleteTerminal(id);
        return isSuccess ? JsonResult.success() : JsonResult.error();
    }

    //批量删除终端
    @RequestMapping(value = "equipment/batchDelTerminal", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult batchDelTerminal(String ids) {
        if(ids == null || ids.equals("")) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        boolean isSuccess = equipmentService.batchDelTerminal(ids);
        return isSuccess ? JsonResult.success() : JsonResult.error();
    }

    //获取中控列表
    @RequestMapping(value = "equipment/consoleList")
    @ResponseBody
    public DataGrid<Console> terminalList(Integer page, Integer rows, Console console) {
        page = page == null ? 1 : page;
        rows = rows == null ? 10 : rows;
        console.setCreaterId(this.getCurrent_user().getCompanyId());//当前登陆人的公司，平台公司
        PageInfo pageInfo = equipmentService.getConsoleList(page, rows, console);
        return new DataGrid(pageInfo);
    }

    //获取代理商绑定中控的列表
    @RequestMapping(value = "equipment/AgentconsoleList",method = RequestMethod.POST)
    @ResponseBody
    public DataGrid<Console> getAgentConsoleList(Integer page, Integer rows, Console console) {
        page = page == null ? 1 : page;
        rows = rows == null ? 10 : rows;
        PageInfo pageInfo = equipmentService.getCompanyAgentConsoleList(page, rows, console);
        return new DataGrid(pageInfo);
    }
    //代理商批量绑定设备
    @RequestMapping(value = "equipment/AgentBindConsole",method = RequestMethod.POST)
    @ResponseBody
    public JsonResult agentBindConsole(String consoleIds,String companyID) {
        if(StringUtils.isBlank(companyID)) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        Console console = new Console();
        console.setAgentId(Long.valueOf(companyID));
        List<Console> consoleList = equipmentService.getConsoleList(1,1000000,console).getList();//获得该代理商已绑定的中控设备
       /* if(!StringUtils.isEmpty(consoleIds)){
            String[] ids = consoleIds.split(",");
            boolean isEqual = true;
            if(!consoleList.isEmpty() && ids.length > 0 && consoleList.size() == ids.length){
                for(int j = 0;j < ids.length;j ++){
                    if(!consoleList.contains(equipmentService.getConsoleById(Long.valueOf(ids[j])))){
                        isEqual = false;
                    }
                    if(isEqual){
                        return new JsonResult(ResultCode.ERROR_CODE,"数据没有改动");
                    }
                }
            }
        }*/
        Iterator i =consoleList.iterator();
        boolean isSuccess = false;
        while (i.hasNext()){
            console = (Console) i.next();
            isSuccess = equipmentService.unBindConsole(console);//挨个解绑
        }
        Console consoleTemp = new Console();
        if (consoleList.isEmpty()||isSuccess){
            if (!StringUtils.isBlank(consoleIds)){
                String [] ids = consoleIds.split(",");
                for (String id: ids
                        ) {
                    consoleTemp.setId(Long.valueOf(id));
                    consoleTemp.setAgentId(Long.valueOf(companyID));
                    consoleTemp.setBindStatus(Byte.valueOf("2"));
                    consoleTemp.setAgentName(companyService.getCompanyByID(companyID).getName());
                    isSuccess = equipmentService.updateConsole(consoleTemp);
                }
            }
        }
        if(consoleIds.isEmpty() && consoleList.isEmpty()){
            isSuccess = true;
        }
        return isSuccess ? JsonResult.success() : JsonResult.error();
    }

    //增加中控
    @RequestMapping(value = "equipment/addConsole")
    @ResponseBody
    public JsonResult addConsole(Console console) {
        if(console == null) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        if(StringUtils.isBlank(console.getMachineCode())) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "机器码不能为空");
        }
        if(StringUtils.isBlank(console.getBusinessCode())) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "业务码不能为空");
        }
        //机器码，业务码去重。
        if(equipmentService.getConsoleByMachineCode(console) != null){
            return new JsonResult(ResultCode.ERROR_CODE, "该机器码已存在");
        }
        if(equipmentService.getConsoleByBusinessCode(console) != null){
            return new JsonResult(ResultCode.ERROR_CODE, "该业务码已存在");
        }
        console.setCreaterId(this.getCurrent_user().getCompanyId());//把当前登陆人的公司作为设备的创建人。
        console.setCreater(this.getCurrent_user().getCompanyName());
        boolean isSuccess = equipmentService.addConsole(console);
        //为设备设置默认计费标准：
        Long consoleIdTemp = equipmentService.getConsoleByConsole(console).getId();
        ChargeStandard chargeStandard = new ChargeStandard();//空实体
        chargeStandard.setCreaterId(this.getCurrent_user().getCompanyId());//当前平台公司的默认计费标准。
        List<ChargeStandard> defaultChargeStandardList = equipmentConfigService.getChargeStandardList(1,100,chargeStandard).getList();//获取默认计费标准

        if(!defaultChargeStandardList.isEmpty()){//赋值
            for(ChargeStandard chargeStandardTemp : defaultChargeStandardList){
                ConsoleChargeStandard consoleChargeStandard = new ConsoleChargeStandard();
                consoleChargeStandard.setCreaterId(this.getCurrent_user().getId());
                consoleChargeStandard.setCreater(this.getCurrent_user().getRealName());
                consoleChargeStandard.setConsoleId(consoleIdTemp);//
                consoleChargeStandard.setPowerLower(chargeStandardTemp.getPowerLower());
                consoleChargeStandard.setPowerUpper(chargeStandardTemp.getPowerUpper());
                consoleChargeStandard.setName(chargeStandardTemp.getName());
                consoleChargeStandard.setUnitRice(chargeStandardTemp.getUnitRice());
                consoleChargeStandard.setUnitType(chargeStandardTemp.getUnitType());
                equipmentConfigService.addConsoleChargeStandard(consoleChargeStandard);
            }
        }

        return isSuccess ? JsonResult.success() : JsonResult.error();
    }
    //编辑中控
    @RequestMapping(value = "equipment/editConsole")
    @ResponseBody
    public JsonResult editConsole(Console console) {
        if(console == null || console.getId() == null) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        if(StringUtils.isBlank(console.getMachineCode())) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "机器码不能为空");
        }
        if(StringUtils.isBlank(console.getBusinessCode())) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "业务码不能为空");
        }
        //机器码，业务码去重。
        if(equipmentService.getConsoleByMachineCode(console) != null){
            return new JsonResult(ResultCode.ERROR_CODE, "该机器码已存在");
        }
        if(equipmentService.getConsoleByBusinessCode(console) != null){
            return new JsonResult(ResultCode.ERROR_CODE, "该业务码已存在");
        }
        boolean isSuccess = equipmentService.updateConsole(console);
        return isSuccess ? JsonResult.success() : JsonResult.error();
    }


    //批量禁用中控
    @RequestMapping(value = "console/batchDisable")
    @ResponseBody
    public JsonResult batchDisableCondole(String ids) {
        //禁用中控
        if(StringUtils.isEmpty(ids)) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        boolean isSuccess = equipmentService.batchDisableConsole(ids);
        return isSuccess ? JsonResult.success() : new JsonResult(ResultCode.ERROR_CODE,"状态未改变");
    }

    //批量禁用中控
    @RequestMapping(value = "console/batchEnable")
    @ResponseBody
    public JsonResult batchEnableCondole(String ids) {
        //禁用中控
        if(StringUtils.isEmpty(ids)) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        boolean isSuccess = equipmentService.batchEnableConsole(ids);
        return isSuccess ? JsonResult.success() : new JsonResult(ResultCode.ERROR_CODE,"状态未改变");
    }

    //禁用中控
    @RequestMapping(value = "equipment/disableConsole", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult disableConsole(Long id) {
        if(id == null || id <= 0) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        boolean isSuccess = equipmentService.updateConsoleStatus(id, Constants.ROLE_STATUS_DISABLE);
        return isSuccess ? JsonResult.success() : JsonResult.error();
    }

    //启用中控
    @RequestMapping(value = "equipment/enableConsole", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult enableConsole(Long id) {
        if(id == null || id <= 0) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        boolean isSuccess = equipmentService.updateConsoleStatus(id, Constants.ROLE_STATUS_ENABLE);
        return isSuccess ? JsonResult.success() : JsonResult.error();
    }
    //删除中控
    @RequestMapping(value = "equipment/deleteConsole", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult deleteConsole(Long id) {
        if(id == null || id <= 0) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        boolean isSuccess = equipmentService.deleteConsole(id);
        return isSuccess ? JsonResult.success() : JsonResult.error();
    }

    //绑定终端
    @RequestMapping(value = "equipment/bindingTerminal", method = RequestMethod.POST)
    @ResponseBody
//    public JsonResult bindingTerminal(Long id, String serialNumber) {
//        if(id == null || serialNumber == null || "".equals(serialNumber)) {
//            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
//        }
//        boolean isSuccess = equipmentService.bindingTerminal(id, serialNumber);
//        return isSuccess ? JsonResult.success() : JsonResult.error();
//    }
    public JsonResult bindingTerminal(Long id, String serialNumber) {
        if(id == null || serialNumber == null || "".equals(serialNumber)) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        return equipmentService.bindingTerminal(id, serialNumber);
    }

    //绑定中控
    @RequestMapping(value = "equipment/bindingConsole", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult bindingConsole(Long id, String serialNumber) {
        if(id == null || serialNumber == null || "".equals(serialNumber)) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        return equipmentService.bindingConsole(id, serialNumber);
    }

    //绑定代理商
    @RequestMapping(value = "equipment/bindingAgent", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult bindingAgent(Long id, String agentName) {
        if(id == null || agentName == null || "".equals(agentName)) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        return equipmentService.bindingAgent(id, agentName);
    }

    //批量删除中控
    @RequestMapping(value = "equipment/batchDelConsole", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult batchDelConsole(String ids) {
        if(ids == null || ids.equals("")) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        boolean isSuccess = equipmentService.batchDelConsole(ids);
        return isSuccess ? JsonResult.success() : JsonResult.error();
    }

    //获取充电站列表
    @RequestMapping(value = "equipment/stationList")
    @ResponseBody
    public DataGrid<ChargingStation> stationList(Integer page, Integer rows, ChargingStation chargingStation) {
        page = page == null ? 1 : page;
        rows = rows == null ? 10 : rows;
        if (chargingStation.getManagerId()==null){
            //判断是不是公司的leader
            if(companyService.getCompanyById(this.getCurrent_user().getCompanyId()).getLeader().equals(this.getCurrent_user().getId())){
                chargingStation.setManagerId(this.getCurrent_user().getCompanyId());//代理商id设置为当前登陆人的公司id。
            }else {
                chargingStation.setCreaterId(this.getCurrent_user().getId());
            }
        }
        PageInfo pageInfo = equipmentService.getChargingStationList(page, rows, chargingStation);
        return new DataGrid(pageInfo);
    }
//    public DataGrid<ChargingStation> stationList(Integer page, Integer rows, ChargingStation chargingStation,Long id) {
//        page = page == null ? 1 : page;
//        rows = rows == null ? 10 : rows;
//        PageInfo pageInfo = equipmentService.getChargingStationList(page, rows, chargingStation);
//        return new DataGrid(pageInfo);
//    }

    //增加充电站
    @RequestMapping(value = "equipment/addStation")
    @ResponseBody
    public JsonResult addStation(ChargingStation chargingStation) {
        if(chargingStation == null) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        if(StringUtils.isBlank(chargingStation.getName())) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "电站名称不能为空");
        }
        if(chargingStation.getPartenerId() != null){
            chargingStation.setPartenerName(companyService.getCompanyById(chargingStation.getPartenerId()).getName());//合作伙伴名称
        }else{
            return new JsonResult(ResultCode.ERROR_CODE,"请转到合作伙伴维护页面的电站维护进行添加");
        }
        chargingStation.setCreaterId(this.getCurrent_user().getId());//创建人id为登陆人id
        chargingStation.setCreater(this.getCurrent_user().getRealName());//创建人名称为登陆人名称
        chargingStation.setManagerId(this.getCurrent_user().getCompanyId());//代理商为登陆人的公司
        chargingStation.setManagerName(companyService.getCompanyById(this.getCurrent_user().getCompanyId()).getName());//代理商公司名称
        boolean isSuccess = equipmentService.addChargingStation(chargingStation);
        return isSuccess ? JsonResult.success() : JsonResult.error();
    }
    //编辑充电站
    @RequestMapping(value = "equipment/editStation")
    @ResponseBody
    public JsonResult editStation(ChargingStation chargingStation) {
        if(chargingStation == null || chargingStation.getId() == null) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        if(StringUtils.isBlank(chargingStation.getName())) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "角色名称不能为空");
        }
        boolean isSuccess = equipmentService.updateChargingStation(chargingStation);
        return isSuccess ? JsonResult.success() : JsonResult.error();
    }

    //禁用充电站
    @RequestMapping(value = "equipment/disableStation", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult disableStation(Long id) {
        if(id == null || id <= 0) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        boolean isSuccess = equipmentService.updateChargingStationStatus(id, Constants.ROLE_STATUS_DISABLE);
        return isSuccess ? JsonResult.success() : JsonResult.error();
    }

    //启用充电站
    @RequestMapping(value = "equipment/enableStation", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult enableStation(Long id) {
        if(id == null || id <= 0) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        boolean isSuccess = equipmentService.updateChargingStationStatus(id, Constants.ROLE_STATUS_ENABLE);
        return isSuccess ? JsonResult.success() : JsonResult.error();
    }
    //删除充电站
    @RequestMapping(value = "equipment/deleteStation", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult deleteStation(Long id) {
        if(id == null || id <= 0) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        boolean isSuccess = equipmentService.deleteChargingStation(id);
        return isSuccess ? JsonResult.success() : JsonResult.error();
    }

    //批量删除充电站
    @RequestMapping(value = "equipment/batchDelStation", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult batchDelStation(String ids) {
        if(ids == null || ids.equals("")) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        boolean isSuccess = equipmentService.batchDelChargingStation(ids);
        return isSuccess ? JsonResult.success() : JsonResult.error();
    }

    //合作伙伴获取设备情况列表（中控+代理商+合作伙伴）
    @RequestMapping(value = "equipment/partnerEquipmentSituationList")
    @ResponseBody
    public DataGrid<Terminal> partnerEquipmentSituationList(Integer page, Integer rows, EquipmentSituation equipmentSituation) {
        page = page == null ? 1 : page;
        rows = rows == null ? 10 : rows;
        equipmentSituation.setPartnerId(this.getCurrent_user().getCompanyId());
        PageInfo pageInfo = equipmentService.getPartnerEquipmentSituationList(page, rows, equipmentSituation);
        return new DataGrid(pageInfo);
    }

    //代理商获取设备情况列表（中控+代理商+合作伙伴）
    @RequestMapping(value = "equipment/agentEquipmentSituationList")
    @ResponseBody
    public DataGrid<Terminal> agentEquipmentSituationList(Integer page, Integer rows, EquipmentSituation equipmentSituation) {
        page = page == null ? 1 : page;
        rows = rows == null ? 10 : rows;
        equipmentSituation.setAgentId(this.getCurrent_user().getCompanyId());
        PageInfo pageInfo = equipmentService.getAgentEquipmentSituationList(page, rows, equipmentSituation);
        return new DataGrid(pageInfo);
    }

    //平台公司获取设备情况列表（中控+代理商+合作伙伴）
    @RequestMapping(value = "equipment/companyEquipmentSituationList")
    @ResponseBody
    public DataGrid<Terminal> companyEquipmentSituationList(Integer page, Integer rows, EquipmentSituation equipmentSituation) {
        page = page == null ? 1 : page;
        rows = rows == null ? 10 : rows;
        equipmentSituation.setCreaterId(this.getCurrent_user().getCompanyId());//此处用createrId存放，实际为登陆人公司id，此处对应平台公司id。
        PageInfo pageInfo = equipmentService.getCompanyEquipmentSituationList(page, rows, equipmentSituation);
        return new DataGrid(pageInfo);
    }


    @RequestMapping(value = "equipment/showTerminal")
    @ResponseBody
    public DataGrid<Terminal> terminalList(Integer page, Integer rows, String consoleId) {
        page = page == null ? 1 : page;
        rows = rows == null ? 10 : rows;
        Terminal terminal = new Terminal();
        terminal.setConsoleId(Long.valueOf(consoleId));
        PageInfo pageInfo = equipmentService.getTerminalList(page,rows,terminal);
        return new DataGrid(pageInfo);
    }

    //批量生成二维码
    @RequestMapping(value = "equipment/batchAddQrCode", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult batchAddQrCode(String ids) {
        if(ids == null || ids.equals("")) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        return equipmentService.batchAddQrCode(ids);
    }

    //批量生成二维码
    @RequestMapping(value = "equipment/batchAddTerminalQrCode", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult batchAddTerminalQrCode(String ids) {
        if(ids == null || ids.equals("")) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        return equipmentService.batchAddTerminalQrCode(ids);
    }

    /**
     * 代理商获取旗下中控，列出供电站进行绑定。（已绑定其他电站的中控不展示）
     * @param page
     * @param rows
     * @param console
     * @return
     */
    @RequestMapping(value = "equipment/agentConsoleList", method = RequestMethod.POST)
    @ResponseBody
    public DataGrid<Console> agentConsoleList(Integer page,Integer rows,Console console) {
        page = page == null ? 1 : page;
        rows = rows == null ? 10 : rows;
        console.setAgentId(this.getCurrent_user().getCompanyId());
        PageInfo pageInfo = equipmentService.getConsoleForStationList(page, rows, console);
        return new DataGrid(pageInfo);
    }

    /**
     * 代理商为电站绑定中控
     * @param consoleIds
     * @param stationId
     * @return
     */
    @RequestMapping(value = "equipment/stationBindConsole",method = RequestMethod.POST)
    @ResponseBody
    public JsonResult stationBindConsole(String consoleIds,String stationId) {
        if(StringUtils.isBlank(stationId)) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        Console console = new Console();
        String [] ids = consoleIds.split(",");
        console.setStationId(Long.valueOf(stationId));
        List<Console> consoleList = equipmentService.getConsoleList(1,1000000,console).getList();//获得之前已绑定到该电站上的中控列表
        //先全部解绑
        Iterator i = consoleList.iterator();
        boolean isUnBindSuccess = false;
        while (i.hasNext()){
            console = (Console) i.next();
            console.setStationId(null);
            console.setPartnerId(null);
            console.setPartnerName(null);
            console.setBindStatus(Byte.valueOf("2"));
            isUnBindSuccess = equipmentService.unBindStationConsole(console);//挨个解绑
        }
        if(consoleList.isEmpty()){
            isUnBindSuccess = true;
        }

        //再把勾选的中控绑定
        boolean isBindSuccess = false;
        if (StringUtils.isBlank(consoleIds)){
            isBindSuccess = true;
        }else{
            for (String id : ids) {
                Console consoleTemp = new Console();
                consoleTemp.setId(Long.valueOf(id));
                consoleTemp.setStationId(Long.valueOf(stationId));
                consoleTemp.setPartnerId(equipmentService.getChargingStationById(Long.valueOf(stationId)).getPartenerId());
                consoleTemp.setPartnerName(equipmentService.getChargingStationById(Long.valueOf(stationId)).getPartenerName());
                consoleTemp.setBindStatus(Byte.valueOf("3"));
                isBindSuccess = equipmentService.updateConsole(consoleTemp);
            }
        }
        return (isUnBindSuccess&&isBindSuccess) ? JsonResult.success() : JsonResult.error();
    }


    /**
     * 批量禁用终端
     * @param ids
     * @return
     */
    @RequestMapping(value = "equipment/batchDisableTerminal",method = RequestMethod.POST)
    @ResponseBody
    public JsonResult batchDisableTerminal(String ids){
        if(StringUtils.isEmpty(ids)) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        boolean isSuccess = equipmentService.batchDisableTerminal(ids);
        return (isSuccess) ? JsonResult.success() : new JsonResult(ResultCode.ERROR_CODE,"状态未改变");
    }

    /**
     * 批量启用终端
     * @param ids
     * @return
     */
    @RequestMapping(value = "equipment/batchEnableTerminal",method = RequestMethod.POST)
    @ResponseBody
    public JsonResult batchEnableTerminal(String ids){
        if(StringUtils.isEmpty(ids)) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        boolean isSuccess = equipmentService.batchEnableTerminal(ids);
        return (isSuccess) ? JsonResult.success() : new JsonResult(ResultCode.ERROR_CODE,"状态未改变");
    }

    //导入Excel
    @RequestMapping(value="equipment/importConsoleExcel", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult importConsoleExcel(MultipartFile file, HttpServletRequest request) throws IOException {
        if (file.isEmpty()){
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "文件为空！");
        }
        String filePath = file.getOriginalFilename();
        InputStream is = file.getInputStream();
        Workbook hssfWorkbook = null;
        if (filePath.endsWith("xlsx")){
            hssfWorkbook = new XSSFWorkbook(is);//Excel 2007
        }else if (filePath.endsWith("xls")){
            hssfWorkbook = new HSSFWorkbook(is);//Excel 2003

        }
        Console console = null;
        boolean isSuccess = false;
        // 循环工作表Sheet
        for (int numSheet = 0; numSheet <hssfWorkbook.getNumberOfSheets(); numSheet++) {
            Sheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
            if (hssfSheet == null) {
                continue;
            }
            // 循环行Row
            for (int rowNum = 0; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
                Row hssfRow = hssfSheet.getRow(rowNum);
                if (hssfRow != null) {
                    console = new Console();
                    //获取机器码
                    Cell machineCode = hssfRow.getCell(0);
                    //获取业务码
                    Cell businessCode = hssfRow.getCell(1);
                    //获取备注
                    Cell remarks = hssfRow.getCell(2);
                    //将单元格内容set进去
                    console.setMachineCode(machineCode.toString());
                    console.setBusinessCode(businessCode.toString());
                    console.setRemarks(remarks.toString());

                    //机器码，业务码去重。
                    if(equipmentService.getConsoleByMachineCode(console) != null){
                        return new JsonResult(ResultCode.ERROR_CODE, "机器码:"+machineCode.toString()+"已存在");
                    }
                    if(equipmentService.getConsoleByBusinessCode(console) != null){
                        return new JsonResult(ResultCode.ERROR_CODE, "业务码:"+businessCode.toString()+"已存在");
                    }
                    console.setCreaterId(this.getCurrent_user().getCompanyId());//把当前登陆人的公司作为设备的创建人。
                    console.setCreater(this.getCurrent_user().getCompanyName());
                    isSuccess = equipmentService.addConsole(console);

                    //为设备设置默认计费标准：
                    Long consoleIdTemp = equipmentService.getConsoleByConsole(console).getId();
                    ChargeStandard chargeStandard = new ChargeStandard();//空实体
                    chargeStandard.setCreaterId(this.getCurrent_user().getCompanyId());//当前平台公司的默认计费标准。
                    List<ChargeStandard> defaultChargeStandardList = equipmentConfigService.getChargeStandardList(1,100,chargeStandard).getList();//获取默认计费标准

                    if(!defaultChargeStandardList.isEmpty()){//赋值
                        for(ChargeStandard chargeStandardTemp : defaultChargeStandardList){
                            ConsoleChargeStandard consoleChargeStandard = new ConsoleChargeStandard();
                            consoleChargeStandard.setCreaterId(this.getCurrent_user().getId());
                            consoleChargeStandard.setCreater(this.getCurrent_user().getRealName());
                            consoleChargeStandard.setConsoleId(consoleIdTemp);//
                            consoleChargeStandard.setPowerLower(chargeStandardTemp.getPowerLower());
                            consoleChargeStandard.setPowerUpper(chargeStandardTemp.getPowerUpper());
                            consoleChargeStandard.setName(chargeStandardTemp.getName());
                            consoleChargeStandard.setUnitRice(chargeStandardTemp.getUnitRice());
                            consoleChargeStandard.setUnitType(chargeStandardTemp.getUnitType());
                            equipmentConfigService.addConsoleChargeStandard(consoleChargeStandard);
                        }
                    }
                }
            }
        }
        return isSuccess ? JsonResult.success() : JsonResult.error();
    }

    //导入Excel
    @RequestMapping(value="equipment/importTerminalExcel", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult importTerminalExcel(MultipartFile file, HttpServletRequest request) throws IOException {
        if (file.isEmpty()){
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "文件为空！");
        }
        String filePath = file.getOriginalFilename();
        InputStream is = file.getInputStream();
        Workbook hssfWorkbook = null;
        if (filePath.endsWith("xlsx")){
            hssfWorkbook = new XSSFWorkbook(is);//Excel 2007
        }else if (filePath.endsWith("xls")){
            hssfWorkbook = new HSSFWorkbook(is);//Excel 2003

        }
        Terminal terminal = null;
        boolean isSuccess = false;
        // 循环工作表Sheet
        for (int numSheet = 0; numSheet <hssfWorkbook.getNumberOfSheets(); numSheet++) {
            Sheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
            if (hssfSheet == null) {
                continue;
            }
            // 循环行Row
            for (int rowNum = 0; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
                Row hssfRow = hssfSheet.getRow(rowNum);
                if (hssfRow != null) {
                    terminal = new Terminal();
                    //获取机器码
                    Cell machineCode = hssfRow.getCell(0);
                    //获取业务码
                    Cell businessCode = hssfRow.getCell(1);
                    //获取备注
                    Cell remarks = hssfRow.getCell(2);
                    //将单元格内容set进去
                    terminal.setMachineCode(machineCode.toString());
                    terminal.setBusinessCode(businessCode.toString());
                    terminal.setRemarks(remarks.toString());
                    //机器码，业务码去重。
                    if(equipmentService.getTerminalByMachineCode(terminal) != null){
                        return new JsonResult(ResultCode.ERROR_CODE, "机器码:"+machineCode.toString()+"已存在");
                    }
                    if(equipmentService.getTerminalByBusinessCode(terminal) != null){
                        return new JsonResult(ResultCode.ERROR_CODE, "业务码:"+businessCode.toString()+"已存在");
                    }
                    terminal.setCreaterId(this.getCurrent_user().getCompanyId());//把当前登陆人的公司作为设备的创建人
                    terminal.setCreater(this.getCurrent_user().getCompanyName());
                    isSuccess = equipmentService.addTerminal(terminal);
                }
            }
        }
        return isSuccess ? JsonResult.success() : JsonResult.error();
    }

    @RequestMapping(value = "equipment/qrDownload")
    @ResponseBody()
    public JsonResult downloadQRCode(String filenames, HttpServletRequest request, HttpServletResponse response){
        if (StringUtils.isBlank(filenames)){
            filenames = request.getParameter("filenames");
            return new JsonResult(ResultCode.PARAM_ERROR_CODE,ResultCode.PARAM_ERROR_MSG);
        }
        String tmpFileName = "QRCode.zip";
        byte[] buffer = new byte[1024];
        File file = new File(SystemCodeConstants.STATIC_DOWNLOAD_BD);
        if (!file.exists()){
           boolean ok = file.mkdir();
        }
        String strZipPath = SystemCodeConstants.STATIC_DOWNLOAD_BD+"/"+tmpFileName;
        String fileNames [] = filenames.split(",");
        try {
            File file1 = new File(strZipPath);
            if (!file1.exists()){
                file1.createNewFile();
            }
            ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(strZipPath));
            for (String name:fileNames
                    ) {
//                InputStream inputStream = OssUtil.getFileFromOss(SystemCodeConstants.OSS_ORBASE_URL+"/"+name);//本地测试用
                InputStream inputStream = OssUtil.getFileFromOss(SystemCodeConstants.OSS_ORBASE_URL+File.separator+name);//OSS下载用
//                InputStream inputStream = new DataInputStream(new FileInputStream("D:/company1terminalbusiness2.png"));//本地测试下载，非OSS下载
                zipOutputStream.putNextEntry(new ZipEntry(name));
                int len;
                while ((len=inputStream.read(buffer))>0){
                    zipOutputStream.write(buffer,0,len);
                }
                inputStream.close();
            }
            zipOutputStream.closeEntry();
            zipOutputStream.flush();
            zipOutputStream.close();

//            //进行浏览器下载
//            //获得浏览器代理信息
            final String userAgent = request.getHeader("USER-AGENT");
            String finalFileName = null;
            response.reset();
            if (userAgent.indexOf("MSIE")>=0){
                //IE 浏览器
                finalFileName = URLEncoder.encode(tmpFileName,"UTF8");
                System.out.println("IE浏览器");
            } else if(userAgent.indexOf("Mozilla")>=0){
                //Google OR Firefox
                finalFileName = new String(tmpFileName.getBytes(), "ISO8859-1");
                System.out.println("Google OR Firefox");
            }else {
                finalFileName = URLEncoder.encode(tmpFileName,"UTF8");//其他浏览器
            }
            //告知浏览器下载文件，而不是直接打开，浏览器默认为打开
            response.setContentType("application/x-download");
            //response.setHeader("Location",finalFileName);
            response.setHeader("Content-Disposition" ,"attachment;filename=\"" +finalFileName+ "\"");
            DataInputStream in = new DataInputStream(new FileInputStream(strZipPath));
            ServletOutputStream servletOutputStream=response.getOutputStream();
            DataOutputStream temps = new DataOutputStream(servletOutputStream);
            byte[] b = new byte[2048];
            int i = -1;
            try {
                while ((i = in.read(b)) != -1) {
                    temps.write(b);
                }
                temps.flush();
            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                if(temps!=null) temps.close();
                if(in!=null) in.close();
                servletOutputStream.close();
                file.delete();
                file1.delete();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }

        return  JsonResult.success();
    }






}
